<?php
/**
 * Created by Red.G
 * Time: 2018/5/28 19:20
 *
 * 基础model类，所有model都应该继承自该类
 * mongodb增删改查文档：https://github.com/jenssegers/laravel-mongodb
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Base extends Model
{

    /**
     * SQL运算
     * @param $v
     * @return bool
     */
    protected static function _operator($operator,&$query,$where)
    {
        switch ( strtolower($operator) ){
            case 'in':
                $query->whereIn($where[0],$where[2]);
                break;
            case 'between':
                $query->whereBetween($where[0],$where[2]);
                break;
            default:
                $query->where([$where]);
                break;
        }
        return $query;
    }

    /**
     * 构建where条件
     * @param $query
     * @param $where = [
     *       [ 'id',1 ],
     *       [ 'id',1 ],
     *  ]
     */
    protected static function _buildWhere(&$query, $where)
    {
        foreach ($where as $k => $v) {
            if (is_array($v)) {
                self::_operator($v[1],$query,$v);
            } else {
                $query->where($k, $v);
            }
        };
        return $query;
    }


    /**
     * 构建select字段
     * @param $query
     * @param $fields
     */
    protected static function _buildSelect(&$query, $fields)
    {
        if (is_array($fields)) {
            foreach ($fields as $k => $v) {
                if ($k == 0) {
                    $query->select($v);
                } else {
                    $query->addSelect($v);
                }
            }
        } else {
            $query->select($fields);
        }
    }
}